package com.moxiao.yfjh.module.member.service.user;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.moxiao.yfjh.framework.common.enums.CommonStatusEnum;
import com.moxiao.yfjh.framework.common.pojo.PageResult;
import com.moxiao.yfjh.framework.mybatis.core.util.MyBatisUtils;
import com.moxiao.yfjh.module.member.controller.admin.user.vo.DistributionVo;
import com.moxiao.yfjh.module.member.controller.admin.user.vo.MemberUserPageReqVO;
import com.moxiao.yfjh.module.member.controller.admin.user.vo.MemberUserRespVO;
import com.moxiao.yfjh.module.member.controller.admin.user.vo.MemberUserUpdateReqVO;
import com.moxiao.yfjh.module.member.controller.app.user.vo.*;
import com.moxiao.yfjh.module.member.controller.app.user.vo.AppMemberUserResetPasswordReqVO;
import com.moxiao.yfjh.module.member.controller.app.user.vo.AppMemberUserUpdateMobileReqVO;
import com.moxiao.yfjh.module.member.controller.app.user.vo.AppMemberUserUpdatePasswordReqVO;
import com.moxiao.yfjh.module.member.controller.app.user.vo.AppMemberUserUpdateReqVO;
import com.moxiao.yfjh.module.member.controller.app.user.vo.AppTeamReqVo;
import com.moxiao.yfjh.module.member.convert.user.MemberUserConvert;
import com.moxiao.yfjh.module.member.dal.dataobject.user.MemberUserDO;
import com.moxiao.yfjh.module.member.dal.mysql.user.MemberUserMapper;
import com.moxiao.yfjh.module.member.mq.producer.user.UserCreateProducer;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.google.common.annotations.VisibleForTesting;
import com.moxiao.yfjh.module.member.enums.ErrorCodeConstants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionSynchronization;
import org.springframework.transaction.support.TransactionSynchronizationManager;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.time.LocalDateTime;
import java.util.Collection;
import java.util.List;
import java.util.Objects;

import static com.moxiao.yfjh.framework.common.exception.util.ServiceExceptionUtil.exception;

/**
 * 会员 User Service 实现类
 *
 * @author mx
 */
@Service
@Valid
@Slf4j
public class MemberUserServiceImpl implements MemberUserService {
    private final static String memberSmsSendKey = "MEMBER_SMS_CODE";
    @Resource
    private MemberUserMapper memberUserMapper;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private PasswordEncoder passwordEncoder;

    @Resource
    private UserCreateProducer registerCouponProducer;


    @Override
    public MemberUserDO getUserByMobile(String mobile) {
        return memberUserMapper.selectByMobile(mobile);
    }

    @Override
    public List<MemberUserDO> getUserListByNickname(String nickname) {
        return memberUserMapper.selectListByNicknameLike(nickname);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public MemberUserDO createUserIfAbsent(String mobile, String registerIp) {
        // 用户已经存在
        MemberUserDO user = memberUserMapper.selectByMobile(mobile);
        if (user != null) {
            return user;
        }
        // 用户不存在，则进行创建
        return createUser(mobile, registerIp);
    }

    private MemberUserDO createUser(String mobile, String registerIp) {
        // 生成密码
        String password = IdUtil.fastSimpleUUID();
        // 插入用户
        MemberUserDO user = new MemberUserDO();
        user.setMobile(mobile);
        user.setStatus(CommonStatusEnum.ENABLE.getStatus()); // 默认开启
        user.setPassword(encodePassword(password)); // 加密密码
        user.setRegisterIp(registerIp);
        memberUserMapper.insert(user);

        // 发送 MQ 消息：用户创建
        TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization() {

            @Override
            public void afterCommit() {
                registerCouponProducer.sendUserCreateMessage(user.getId());
            }

        });
        return user;
    }

    @Override
    public void updateUserLogin(Long id, String loginIp) {
        memberUserMapper.updateById(new MemberUserDO().setId(id)
                .setLoginIp(loginIp).setLoginDate(LocalDateTime.now()));
    }

    @Override
    public MemberUserDO getUser(Long id) {
        return memberUserMapper.selectById(id);
    }

    @Override
    public List<MemberUserDO> getUserList(Collection<Long> ids) {
        if (CollUtil.isEmpty(ids)) {
            return ListUtil.empty();
        }
        return memberUserMapper.selectBatchIds(ids);
    }

    @Override
    public void updateUser(Long userId, AppMemberUserUpdateReqVO reqVO) {
        memberUserMapper.updateById(new MemberUserDO().setId(userId)
                .setNickname(reqVO.getNickname()).setAvatar(reqVO.getAvatar()));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateUserMobile(Long userId, AppMemberUserUpdateMobileReqVO reqVO) {
        // 检测用户是否存在
        MemberUserDO user = validateUserExists(userId);
        // 校验新手机是否已经被绑定
        validateMobileUnique(null, reqVO.getMobile());

        String redisKey = memberSmsSendKey + reqVO.getMobile();
        String code = stringRedisTemplate.opsForValue().get(redisKey);
        //校验验证码
        Assert.notNull(Objects.equals(reqVO.getCode(),code), "获取验证码失败");

        // 更新用户手机
        memberUserMapper.updateById(MemberUserDO.builder().id(userId).mobile(reqVO.getMobile()).build());
    }

    @Override
    public void updateUserPassword(Long userId, AppMemberUserUpdatePasswordReqVO reqVO) {
        // 检测用户是否存在
        MemberUserDO user = validateUserExists(userId);
        Assert.notNull(Objects.nonNull(user), "获取验证码失败");
        // 校验验证码
        String redisKey = memberSmsSendKey + user.getMobile();
        String s = stringRedisTemplate.opsForValue().get(redisKey);
        //校验验证码
        Assert.notNull(Objects.equals(reqVO.getCode(),s), "获取验证码失败");

        // 更新用户密码
        memberUserMapper.updateById(MemberUserDO.builder().id(userId)
                .password(passwordEncoder.encode(reqVO.getPassword())).build());
    }

    @Override
    public void resetUserPassword(AppMemberUserResetPasswordReqVO reqVO) {
        // 检验用户是否存在
        MemberUserDO user = validateUserExists(reqVO.getMobile());

        // 使用验证码
        String redisKey = memberSmsSendKey + reqVO.getMobile();
        String s = stringRedisTemplate.opsForValue().get(redisKey);
        //校验验证码
        Assert.notNull(Objects.equals(reqVO.getCode(),s), "获取验证码失败");


        // 更新密码
        memberUserMapper.updateById(MemberUserDO.builder().id(user.getId())
                .password(passwordEncoder.encode(reqVO.getPassword())).build());
    }

    private MemberUserDO validateUserExists(String mobile) {
        MemberUserDO user = memberUserMapper.selectByMobile(mobile);
        if (user == null) {
            throw com.moxiao.yfjh.framework.common.exception.util.ServiceExceptionUtil.exception(
                    ErrorCodeConstants.USER_MOBILE_NOT_EXISTS);
        }
        return user;
    }

    @Override
    public boolean isPasswordMatch(String rawPassword, String encodedPassword) {
        return passwordEncoder.matches(rawPassword, encodedPassword);
    }

    /**
     * 对密码进行加密
     *
     * @param password 密码
     * @return 加密后的密码
     */
    private String encodePassword(String password) {
        return passwordEncoder.encode(password);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateUser(MemberUserUpdateReqVO updateReqVO) {
        // 校验存在
        validateUserExists(updateReqVO.getId());
        // 校验手机唯一
        validateMobileUnique(updateReqVO.getId(), updateReqVO.getMobile());

        // 更新
        MemberUserDO updateObj = MemberUserConvert.INSTANCE.convert(updateReqVO);
        memberUserMapper.updateById(updateObj);
    }

    @VisibleForTesting
    MemberUserDO validateUserExists(Long id) {
        if (id == null) {
            return null;
        }
        MemberUserDO user = memberUserMapper.selectById(id);
        if (user == null) {
            throw com.moxiao.yfjh.framework.common.exception.util.ServiceExceptionUtil.exception(
                    ErrorCodeConstants.USER_NOT_EXISTS);
        }
        return user;
    }

    @VisibleForTesting
    void validateMobileUnique(Long id, String mobile) {
        if (StrUtil.isBlank(mobile)) {
            return;
        }
        MemberUserDO user = memberUserMapper.selectByMobile(mobile);
        if (user == null) {
            return;
        }
        // 如果 id 为空，说明不用比较是否为相同 id 的用户
        if (id == null) {
            throw com.moxiao.yfjh.framework.common.exception.util.ServiceExceptionUtil.exception(
                    ErrorCodeConstants.USER_MOBILE_USED, mobile);
        }
        if (!user.getId().equals(id)) {
            throw com.moxiao.yfjh.framework.common.exception.util.ServiceExceptionUtil.exception(
                    ErrorCodeConstants.USER_MOBILE_USED, mobile);
        }
    }

    @Override
    public PageResult<MemberUserDO> getUserPage(MemberUserPageReqVO pageReqVO) {
        return memberUserMapper.selectPage(pageReqVO);
    }

    @Override
    public void updateUserLevel(Long id, Long levelId, Integer experience) {
        // 0 代表无等级：防止UpdateById时，会被过滤掉的问题
        levelId = ObjectUtil.defaultIfNull(levelId, 0L);
        memberUserMapper.updateById(new MemberUserDO()
                .setId(id)
                .setLevelId(levelId).setExperience(experience)
        );
    }

    @Override
    public Long getUserCountByGroupId(Long groupId) {
        return memberUserMapper.selectCountByGroupId(groupId);
    }

    @Override
    public Long getUserCountByLevelId(Long levelId) {
        return memberUserMapper.selectCountByLevelId(levelId);
    }

    @Override
    public Long getUserCountByTagId(Long tagId) {
        return memberUserMapper.selectCountByTagId(tagId);
    }

    @Override
    public boolean updateUserPoint(Long id, Integer point) {
        if (point > 0) {
            memberUserMapper.updatePointIncr(id, point);
        } else if (point < 0) {
            return memberUserMapper.updatePointDecr(id, point) > 0;
        }
        return true;
    }

    @Override
    public List<AppTeamReqVo> getTeamList(Long userId) {
        List<AppTeamReqVo> list = memberUserMapper.getTeamList(String.valueOf(userId));
        return list;
    }

    @Override
    public PageResult<MemberUserRespVO> getDistributorsList(MemberUserPageReqVO pageVO) {
        IPage<MemberUserRespVO> pageResult = memberUserMapper.getDistributorsList(MyBatisUtils.buildPage(pageVO), pageVO.getMobile(), pageVO.getNickname());
        pageResult.getRecords().stream().forEach(item -> {
            //团队人数
            item.setTeam(memberUserMapper.getTeam(String.valueOf(item.getId())));
            // 累计业绩
            item.setPerformance(memberUserMapper.getPerformance(String.valueOf(item.getId())));
        });
        return new PageResult<>(pageResult.getRecords(), pageResult.getTotal());
    }

    @Override
    public DistributionVo getDistributionInfo(Long id) {
        DistributionVo vo = new DistributionVo();
        //团队人数
        vo.setTeam(memberUserMapper.getTeam(String.valueOf(id)));
        // 累计业绩
        vo.setPerformance(memberUserMapper.getPerformance(String.valueOf(id)));
        return vo;
    }
}
